//
//  AppDelegate.swift
//  仿一个新浪微博
//
//  Created by 孙家林 on 15/9/9.
//  Copyright © 2015年 sunjialin. All rights reserved.
//

import UIKit

let HMRootViewControllerSwitchNotification = "HMRootViewControllerSwitchNotification"

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?


    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        
        //注册 通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "switchViewController:", name: HMRootViewControllerSwitchNotification, object: nil)
        
        print(UserAccount.loadAccount())
        
        ///设置外观
        setUpAppearance()
            
        window = UIWindow(frame: UIScreen.mainScreen().bounds)
            
        window?.backgroundColor = UIColor.whiteColor()
            
        window?.rootViewController = defaultViewController()
            
        window?.makeKeyAndVisible()
        
        return true
    }
    
    //注销通知,只是一个习惯
    deinit {
    
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    //切换控制器，一定要在AppDelegate中统一修改
    func switchViewController(n:NSNotification) {
    
        let mainVC = n.object as! Bool
        
        window?.rootViewController  = mainVC ? MainViewController() : WelcomeViewController()
    }
    
    //返回启动默认控制器
    private func defaultViewController() -> UIViewController {
    
        //1、判断用户是否登录，如果没有但呢个路就返回主控制器
        if !UserAccount.userLogin {
            return MainViewController()
        }
        
        //2、判断是否是新版本，如果是。返回新特性，否则返回欢迎界面
        return isNewUpdate() ? NewFeatureCollectionViewController() : WelcomeViewController()
    }
    
    //检查是否是新版本
    private func isNewUpdate() -> Bool {
        
        //1、获取程序当前版本
        let currentVersion = Double(NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"] as! String)!
        
        //2、获取程序之前的版本，偏好设置
        let sandboxVersionKey = "sanboxVersionKey"
        let sandboxVersion = NSUserDefaults.standardUserDefaults().doubleForKey(sandboxVersionKey)
        
        //3、将当前版本保存到偏好设置
        NSUserDefaults.standardUserDefaults().setDouble(currentVersion, forKey: sandboxVersionKey)
        // iOS 7.0 之后，就不需要同步了，iOS 6.0 之前，如果不同步不会第一时间写入沙盒
        NSUserDefaults.standardUserDefaults().synchronize()
        
        //4、返回比较结果
        return currentVersion > sandboxVersion
    }

    private func setUpAppearance() {
            
        ///一经设置，全局有效
        UINavigationBar.appearance().tintColor = UIColor.orangeColor()
            
        UITabBar.appearance().tintColor = UIColor.orangeColor()
    }

}
